//
//  PlayerViewController.m
//  AVPlayer播放网络_本地视频
//
//  Created by Gollum on 16/8/20.
//  Copyright © 2016年 Gollum. All rights reserved.
//

#import "PlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#define WIDTH _viewOfPlayer.bounds.size.width
#define HEIGHT _viewOfPlayer.bounds.size.height
#define RATIO HEIGHT / WIDTH
@interface PlayerViewController ()

@property (nonatomic,strong)AVPlayer *player;
@property (nonatomic,strong)AVPlayerItem *playerItem;
@property (nonatomic,strong)AVPlayerLayer *playerLayer;
@property (nonatomic,assign)CGFloat totalMovieDuration;//该视频的总时长,用来快进快退
@property (nonatomic,strong)UIStepper *stepper;
//默认为0
@property (nonatomic,assign)BOOL isTap;
@property (nonatomic,assign)BOOL isPlay;
@property (nonatomic,assign)BOOL isOpen;

@property (weak, nonatomic) IBOutlet UIView *viewOfPlayer;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *playerButton;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UIView *volumeView;
@property (weak, nonatomic) IBOutlet UIButton *volumeButton;
@property (weak, nonatomic) IBOutlet UISlider *volumeSlider;

@property (weak, nonatomic) IBOutlet UIView *brightnessView;

@property (weak, nonatomic) IBOutlet UISlider *brightnessSlider;





- (IBAction)playerButtonAction:(id)sender;
- (IBAction)progressSliderAction:(id)sender;

- (IBAction)volumButtonAction:(id)sender;
- (IBAction)volumSliderAction:(id)sender;
- (IBAction)brightnessSliderAction:(id)sender;


@end

@implementation PlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化播放器
    [self addAVPlayer];
    _progressSlider.minimumValue = 0;

    //添加通知
    [self addNotificationCenters];
    //播放
   [self.player play];
    //添加手势
    [self addGestureRecognizer];
    //添加进度观察
    [self addProgressObserver];
    //初始时间
    self.timeLabel.text = @"00:00/00:00";
    //初始音量
    self.volumeSlider.value = 0.5f;
    _volumeSlider.minimumValue = 0.0f;
    _volumeSlider.maximumValue = 1.0f;
    
    
    //设置亮度
    self.brightnessSlider.value = 0.5f;
    _brightnessSlider.minimumValue = 0.0f;
    _brightnessSlider.maximumValue = 1.0f;
    
    //将音量滑动条设为垂直方向
    _brightnessView.transform = CGAffineTransformMakeRotation(- M_PI / 2);
    _volumeView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
   // _volumeView.center = CGPointMake(_viewOfPlayer.center.x * 4 / 3,_viewOfPlayer.center.y);
}
#pragma mark - 添加视频播放控件
- (void)addAVPlayer{
    //http://cctv1.vtime.cntv.cloudcdn.net/cache/12_/seg0/index.m3u8?AUTH=KDumCPYYPzSTcmtewPt/u78MdD6mwSpceXl98vdwcN8RIWA7hZqDK8s3RWkdW3PymV7TkVLHQ5UJp1gHXtkWGg==
    //http://flv2.bn.netease.com/videolib3/1505/24/HYUCE6348/SD/HYUCE6348-mobile.mp4
    //播放网络视频
    //处理数据
    //NSString *urlStr = @"http://flv2.bn.netease.com/videolib3/1505/24/HYUCE6348/SD/HYUCE6348-mobile.mp4";
    //
    //urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //NSURL *url = [NSURL URLWithString:urlStr];
    //创建视频播放对象
    //self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    //self.playerItem = [AVPlayerItem playerItemWithURL:url];
    
    //播放本地视频
    NSURL *sourceMoviewUrl = [NSURL fileURLWithPath:@"/Users/tusm/Desktop/播放器/AVPlayer播放网络_本地视频/AVPlayer播放网络_本地视频/Star Wars  Episode VII - The Force Awakens Official Teaser Trailer #1 (2015) - J.J. Abrams Movie HD.mp4"];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMoviewUrl options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    
    //创建视频播放器对象
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    //创建承载播放器的AVPlayerLayer对象
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    //视频填充模式
    //AVLayerVideoGravityResizeAspect 保持纵横比；适合层范围内。
    //AVLayerVideoGravityResize 拉伸填充层边界
    //保持纵横比；填充层边界。
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //将视频播放器添加到playerView的layer层上(三种添加方式above,below)
    //[self.viewOfPlayer.layer insertSublayer:_playerLayer atIndex:0];
    
    [_viewOfPlayer.layer addSublayer:_playerLayer];
    self.playerLayer.frame = CGRectMake(0, 0,self.view.frame.size.width , self.view.frame.size.width * 9.0 / 16.0);
    
    _viewOfPlayer.frame = CGRectMake(0, 20, CGRectGetWidth(_playerLayer.frame), CGRectGetHeight(_playerLayer.frame));
    
    
    
    
    [_playerButton setImage:[UIImage imageNamed:@"player_btn_pause_normal"] forState:UIControlStateNormal];
}

#pragma mark - 添加观察者 观察播放 观察屏幕的旋转
- (void)addNotificationCenters{
    //注册观察者,观察是否完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //注册观察屏幕的旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];

}

- (void)statusBarOrientationChange:(NSNotification *)notification{

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIUserInterfaceLayoutDirectionLeftToRight) {
        NSLog(@"向右横屏");
        [self setplayerlayerFrame];
    }
    if (orientation == UIUserInterfaceLayoutDirectionRightToLeft) {
        NSLog(@"向左横屏");
        [self setplayerlayerFrame];
    }
    if (orientation == UIInterfaceOrientationPortrait) {
        [self setVerticalFrame];
        NSLog(@"竖屏");
    }
}
//横屏时的 frame
- (void)setplayerlayerFrame{
    
    self.playerLayer.frame = CGRectMake(0, 0, HEIGHT, WIDTH );
    
}

//竖屏时的 frame

- (void)setVerticalFrame{
    
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH , HEIGHT);
    
}

- (void)moviePlayDidEnd:(NSNotification *)notify{
    NSLog(@"视频播放完毕");
}
#pragma mark - 添加轻拍手势,隐藏按钮界面
- (void)addGestureRecognizer{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];

    [self.view addGestureRecognizer:tap];
}
//隐藏bottomView
- (void)dismissAllSubViews{
    if (self.isTap == NO) {
        [UIView animateWithDuration:0.5 animations:^{
            _bottomView.alpha = 0;
            _volumeView.alpha = 0;
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            _bottomView.alpha = 1;
            _volumeView.alpha = 1;
        }];
    }
    self.isTap = !_isTap;
}
#pragma mark - 添加进度观察

- (void)addProgressObserver{
    
    __block typeof(self) weakSelf = self;
    //设置(1,1) 设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
        //当前时间
        CGFloat current = CMTimeGetSeconds(weakSelf.player.currentTime);
        //倒计时
        CGFloat rem = duration - current;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
        
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
        weakSelf.timeLabel.text = timeStr;
        
        //保存总时长用于手动快进和快退
        weakSelf.totalMovieDuration = duration;
        //设置进度值 当前时间/总时长
        weakSelf.progressSlider.value = current/duration;
        
    }];


}

- (IBAction)playerButtonAction:(id)sender {
    if (_isPlay) {
        [self.player pause];
         [_playerButton setImage:[UIImage imageNamed:@"player_btn_play_normal"] forState:UIControlStateNormal];
    }
    else{
        [self.player play];
         [_playerButton setImage:[UIImage imageNamed:@"player_btn_pause_normal"] forState:UIControlStateNormal];
    }
    _isPlay = !_isPlay;
}
/*
 CMTimeMake是用來建立CMTime用的,
 CMTime可是专门用来表示视频时间的,
 用法: CMTimeMake(time, timeScale)
 
 time指的就是时间(不是秒),
 而时间要换成秒就要看第二个参数timeScale了.
 timeScale指的是1秒需要由多少帧率构成,
 真正表示时间秒是 time / timeScale .
 
 CMTime curFrame = CMTimeMake(第几帧， 帧率）
 
 */

- (IBAction)progressSliderAction:(id)sender {
    
    UISlider *slider = sender;
    //获取当前时间,value默认值为0;
    double currentTime = self.totalMovieDuration * slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        [self.player play];
    }];
    
}

- (IBAction)volumButtonAction:(id)sender {
    
    if (_isOpen) {
        _player.volume = 0.0f;
        [_volumeButton setImage:[UIImage imageNamed:@"静音"] forState:UIControlStateNormal];
    }
    else{
        _player.volume = _volumeSlider.value;
        [_volumeButton setImage:[UIImage imageNamed:@"音量"] forState:UIControlStateNormal];
    }
    _isOpen = !_isOpen;
}

- (IBAction)volumSliderAction:(id)sender {
    
    //UISlider *slider = sender;
   // double currentVolume = slider.value;
   // UIStepper *stepper = [[UIStepper alloc] init];

    //slider.value = stepper.value;
    //获取当前音量
   // _player.volume = slider.value;
    
    //作品音量控制
    self.player.volume = _volumeSlider.value;
}

//调节亮度
- (IBAction)brightnessSliderAction:(id)sender {
    
    [[UIScreen mainScreen] setBrightness:_brightnessSlider.value];
    
}

































- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
